﻿using FXPushService;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace webapiproxy
{
    /// <summary>
    /// lnfloodapi 的摘要说明
    /// </summary>
    public class lnfloodapi : IHttpHandler
    {
        Model1 _db = new Model1();
        public void ProcessRequest(HttpContext context)
        {
            ApiResult result = null;
            string action = context.Request["action"];
            if (string.IsNullOrEmpty(action)) return;
            action = action.ToUpper();
            if (action.Equals("LOGIN"))
            {
                string username = context.Request["username"];
                string password = context.Request["password"];
                result = Login(username, password);
            }
            else
            {

                result = IsAuthorized(context);


                if (result.success)
                {
                    switch (action)
                    {
                        case "GETRIVER":
                            result = GetRiver();
                            break;
                        case "GETRESERVOIR":
                            result = GetResinfo();
                            break;
                        case "GETDAYRAIN":
                            result = GetDayRain();
                            break;

                    }

                }



            }
            //禁用缓存

            context.Response.AddHeader("Expires", "0");
            context.Response.AddHeader("Cache-Control", "no-cache");
            context.Response.AddHeader("Pragma", "no-cache");
            context.Response.Write(JsonConvert.SerializeObject(result));
            context.Response.End();
        }

    

        public ApiResult GetRiver()
        {
            ApiResult result = new ApiResult();
            //HttpResponseParameter responseParameter1 = HttpUtil.Excute(new HttpRequestParameter
            //{
            //    Url = "http://10.21.5.211:8080/lnflood/app/hydro/riverinfo",
            //    IsPost = false,
            //    Encoding = Encoding.UTF8

            //});
            //result.success = true;
            //try
            //{
            //    var resarray = JsonConvert.DeserializeObject<List<river>>(responseParameter1.Body);
            //    var temp = resarray.Where(o =>
            //    {
            //        if (string.IsNullOrEmpty(o.addvcd)) return false;
            //        return o.addvcd.StartsWith("2111");
            //    });
            //    result.data = temp.ToList();
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}
            result.data = _db.river.ToList();
            return result;
        }

        public ApiResult GetResinfo()
        {
            ApiResult result = new ApiResult();
            //HttpResponseParameter responseParameter1 = HttpUtil.Excute(new HttpRequestParameter
            //{
            //    Url = "http://10.21.5.211:8080/lnflood/app/hydro/resinfo",
            //    IsPost = false,
            //    Encoding = Encoding.UTF8

            //});
            //result.success = true;
            //try
            //{
            //    var resarray = JsonConvert.DeserializeObject<resinfo>(responseParameter1.Body);
            //    var temp = resarray.items.Where(o =>
            //    {

            //        if (string.IsNullOrEmpty(o.addvcd)) return false;
            //        return o.addvcd.StartsWith("2111");
            //    });
            //    result.data = temp.ToList();
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}
            result.data = _db.reservior.ToList();
            return result;
        }

        public ApiResult GetDayRain()
        {
            ApiResult result = new ApiResult();
            //HttpResponseParameter responseParameter1 = HttpUtil.Excute(new HttpRequestParameter
            //{
            //    Url = "http://10.21.5.211:8080/lnflood/app/hydro/dayrain",
            //    IsPost = false,
            //    Encoding = Encoding.UTF8

            //});
            //result.success = true;
            //try
            //{
            //    var resarray = JsonConvert.DeserializeObject<raininfo>(responseParameter1.Body);
            //    var temp = resarray.data.Where(o =>
            //    {

            //        if (string.IsNullOrEmpty(o.addvcd)) return false;
            //        return o.addvcd.StartsWith("2111");
            //    });
            //    result.data = temp.ToList();
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}
            result.data= _db.dayrain.ToList();
            return result;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public ApiResult Login(string username, string password)
        {
            ApiResult rs = new ApiResult();
            string user= ConfigurationManager.AppSettings["username"];
            string pwd=      ConfigurationManager.AppSettings["password"];
            //假设用户名为"admin"，密码为"123"
            if (username == user && password == pwd)
            {
                //如果用户登录成功，则可以得到该用户的身份数据。当然实际开发中，这里需要在数据库中获得该用户的角色及权限
                AuthInfo authInfo = new AuthInfo
                {
                    IsAdmin = true,
                    Roles = new List<string> { "admin", "owner" },
                    UserName = "admin"
                };
                try
                {

                    //生成token,SecureKey是配置的web.config中，用于加密token的key，
                    var secret = ConfigurationManager.AppSettings["SecureKey"];

                    var payload = new AuthInfo()
                    {
                        IsAdmin = true,
                        Roles = new List<string> { "admin", "owner" },
                        UserName = "admin"
                    };


                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                    IJsonSerializer serializer = new JsonNetSerializer();
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

                    var token = encoder.Encode(payload, secret);
                    Console.WriteLine(token);

                    rs.data = token;
                    rs.success = true;

                }
                catch
                {
                    rs.success = false;
                    rs.msg = "登陆失败";
                }
            }
            else
            {
                rs.success = false;
                rs.msg = "用户名或密码不正确";
            }

            return rs;
        }


        protected ApiResult IsAuthorized(HttpContext context)
        {
            //前端请求api时会将token存放在名为"auth"的请求头中

            var authHeader = context.Request.Headers.Get("auth");
            ApiResult result = new ApiResult();
            if (authHeader != null)
            {
                string token = authHeader;
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        //对token进行解密
                        string secret = ConfigurationManager.AppSettings["SecureKey"];



                        try
                        {
                            IJsonSerializer serializer = new JsonNetSerializer();
                            IDateTimeProvider provider = new UtcDateTimeProvider();
                            IJwtValidator validator = new JwtValidator(serializer, provider);
                            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);

                            //AuthInfo authInfo = decoder.DecodeToObject<AuthInfo>(token, secret, verify: true);

                            var authInfo = decoder.DecodeToObject(token, secret, verify: false);
                            Console.WriteLine(authInfo);
                            result.success = true;

                        }
                        catch (TokenExpiredException)
                        {
                            result.msg = "Token has expired";
                            result.success = false;
                        }
                        catch (SignatureVerificationException)
                        {
                            result.msg = "Token has invalid signature";
                            result.success = false;
                        }



                    }
                    catch
                    {
                        result.success = false;
                        result.msg = "认证失败";
                    }
                }
                else
                {
                    result.success = false;
                    result.msg = "认证失败";
                }
            }
            else
            {
                result.success = false;
                result.msg = "认证失败";
            }

            return result;
        }




    }
}